import 'package:flutter/material.dart';
import 'package:sharing/model/book.dart';
import 'package:sharing/utils/whole_apis.dart';
import 'package:sharing/model/book_list_item.dart';
import 'package:sharing/model/book_info_comment.dart';
import 'package:sharing/utils/whole_apis.dart';
import 'package:sharing/net/net_util.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sharing/net/ris_read_apis.dart';
import 'package:sharing/model/history.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:sharing/net/ris_read_apis.dart';
import 'package:sharing/utils/whole_apis.dart';
import "package:sharing/ui/widget/read_pdf_file_widget.dart";
import 'dart:convert';
class BookInfo extends StatefulWidget {
  final Book book;

  BookInfo({@required this.book});

  @override
  _BookInfoState createState() => _BookInfoState();
}

class _BookInfoState extends State<BookInfo> {
  List<BookInfoComment> bookInfoComments = [];

  String _content = "";

  void _comments() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String authorization = await prefs.getString("authorization");
    NetUtil.originGet(
        WholeApis.hostName +
            RisReadApis.bookComment +
            "?bookInfoComId=${widget.book.id}",
        Options(headers: {"authorization": authorization}),
        (Response response) {
      print("response >>  ${response.data}");

      if (response.data["code"] == 200 && response.data["message"] != null) {
        print("data ${response.data["message"]}");
        bookInfoComments = BookInfoComment.fromJson(response.data["message"]);
        print("data ok ");
        setState(() {});
      } else {
        print("response not 200 or ${response.data['message']}");
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _comments();
  }

  List<Widget> generates() {
    List<Widget> _list = [];
    _list.add(// 书籍的简介
        _BookInfoWithInfoHeader(
      book: widget.book,
    ));

    for (int i = 0; i < bookInfoComments.length; i++) {
      _list.add(_BookInfoCommentItem(
        comment: bookInfoComments[i],
      ));
      // print("comment ${bookInfoComments[i]}");
    }
    return _list;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        title: Text(widget.book.name),
      ),
      body: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          Container(
            // 下边距设置成 52 避免遮挡
            margin: const EdgeInsets.only(bottom: 52),
            child: SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: Column(
                mainAxisSize: MainAxisSize.max,
                children: generates(),
              ),
            ),
          ),
          // 评论内容的输入
          Positioned(
            bottom: 0,
            left: 0.0,
            right: 0.0,
            height: 52,
            child: Container(
              color: Colors.red,
              child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      onChanged: _commentContentChanged,
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.only(right: 8.0, left: 8.0),
                    decoration: BoxDecoration(),
                    child: GestureDetector(
                      child: Text("评论"),
                      onTap: _commitContent,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _commentContentChanged(String value) {
    _content = value;
  }

  void _commitContent() async {
    // todo
    print("todo $_content");

    SharedPreferences prefs = await SharedPreferences.getInstance();
    String authorization = await prefs.getString("authorization");
    NetUtil.originPost(
        WholeApis.hostName + RisReadApis.commitBookComment,
        Options(headers: {
          "authorization": authorization,
        }, data: {
          "book_info_id": widget.book.id,
          "content": _content
        }), (Response response) {
      print("response ${response.data}");

      if (response.data["code"] == 200 && response.data["message"] != null) {
        var data = response.data["message"];
        BookInfoComment bkcomment = BookInfoComment();
        print("data is${data['publish_time']} && ${data} && ");
        bkcomment.publishTime = DateTime.now();
        bkcomment.content = data["content"];
        bkcomment.scanTimes = data["scan_times"];
        var user = data["user_info"];
        bkcomment.cover = user["cover"];
        bkcomment.userName = user["username"];
        bookInfoComments.insert(0, bkcomment);

        setState(() {
          // todo
        });
      }
    });
  }
}

class _BookInfoWithInfoHeader extends StatelessWidget {
  final Book book;

  _BookInfoWithInfoHeader({@required this.book});

  // 加载图书文件 pdf
  Future<File> _createFileOfPdfUrl() async {
    String dir = (await getApplicationDocumentsDirectory()).path;
    // 分割文件名
    List<String> splits = book.saveName.split("/");
    String localPath = "$dir/${splits[splits.length - 1]}"; //
    print("path ${localPath}");
    var file = new File(localPath);

    bool exists = await file.existsSync();
    if (exists) {
      return file;
    } else {
      String url = "${WholeApis.hostName}/${book.saveName}";
      await Dio().download(url, file.path);
      var preferences = await SharedPreferences.getInstance();
      String  sp = preferences.getString("histories");
      LocalHistories histories = new LocalHistories();
      if (sp == null) {
        var history = LocalHistory(pdfPath: file.path,coverUrl: "",lastTime: DateTime.now(),process: 0);
        histories.localHistories = [];
        histories.localHistories.add(history);
        preferences.setString("histories",json.encode(histories.toJson()) );
      }else{
        var history = LocalHistory(pdfPath: file.path,coverUrl: "static/img/117547d5a84900f03db6e66b5273b3c0snapshot_1551485694336.png",lastTime: DateTime.now(),process: 0);
        histories = LocalHistories.fromJson(json.decode(sp));
        histories.localHistories.add(history);
        preferences.setString("histories",json.encode(histories.toJson()) );
      }
      return file;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 8.0),
      child: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  // 构建图片封面
                  _buildCover(book),
                  Expanded(
                    child: Container(
                      height: 160,
                      color: Colors.black12,
                      margin: const EdgeInsets.only(left: 8.0),
                      child: Column(
                        mainAxisSize: MainAxisSize.max,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          // 标题
                          Container(
                            child: Text(
                              "书名: " + book.name,
                              style: TextStyle(
                                fontSize: 16.0,
                                fontWeight: FontWeight.bold,
                              ),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),

                          // 作者
                          Container(
                            child: Text(
                              "作者: " + book.author,
                              style: TextStyle(
                                fontWeight: FontWeight.normal,
                                fontSize: 14,
                                color: Colors.blueGrey,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),

                          // 版权消息
                          Container(
                            child: Text(
                              "版权© " +
                                  // 这里必须要个括号括起来
                                  (book.copyRight == null
                                      ? ""
                                      : book.copyRight),
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.black38,
                              ),
                            ),
                          ),

                          // 阅读奖励
                          Container(
                            child: Text(
                              "奖励: " + book.reviews_score.toString(),
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.normal,
                                color: Colors.grey[700],
                              ),
                            ),
                          ),

                          Expanded(
                            child: Container(
                              color: Colors.orange,
                              alignment: Alignment.bottomCenter,
                              child: Container(
                                padding: const EdgeInsets.all(8.0),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    Container(
                                      child: RaisedButton(
                                        onPressed: () {
                                          // todo
                                          print("添加书单");
                                        },
                                        child: Text("书单"),
                                      ),
                                    ),
                                    Container(
                                      child: RaisedButton(
                                        onPressed: () async {
                                          // todo
                                          print("直接阅读 ${book}");

                                          _pushHistory(book);
                                          await _createFileOfPdfUrl()
                                              .then((File file) {
                                            // 跳转到图书阅读页面
                                            Navigator.of(context).push(
                                                MaterialPageRoute(
                                                    builder: (context) {
                                                      return ReadPdfFileWidget(
                                                        book: book,
                                                        pdfPath: file.path,
                                                      );
                                                    }));
                                          });
                                        },
                                        child: Text("阅读"),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                          //
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 4.5,
              child: Container(
                margin: const EdgeInsets.only(top: 4),
                color: Colors.black26,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _pushHistory(Book book) async {
    // todo
    print("todo history");

    SharedPreferences prefs = await SharedPreferences.getInstance();
    String authorization = await prefs.getString("authorization");
    NetUtil.originPost(
        WholeApis.hostName + RisReadApis.histories,
        Options(headers: {
          "authorization": authorization,
        }, data: {
          "book": book.saveName,

        }), (Response response) {
      print("response ${response.data}");


    });
  }

  // 构建图片封面
  Widget _buildCover(Book book) {
    return Container(
      // margin: const EdgeInsets.only(top: 8.0),
      height: 160,
      width: 120,
      color: Colors.orange,
      child: Image.network(
        book.cover == null ||
                book.cover == "" ||
                book.cover.startsWith("https://av")
            ? WholeApis.defaultImg
            : WholeApis.hostName + "/${book.cover}",
        fit: BoxFit.cover,
      ),
    );
  }
}

class _BookInfoCommentItem extends StatelessWidget {
  BookInfoComment comment;

  _BookInfoCommentItem({@required this.comment});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 108,
      padding: const EdgeInsets.all(8.0),
      child: Column(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                CircleAvatar(
                  backgroundImage: NetworkImage(
                      comment.cover == null || comment.cover == ""
                          ? WholeApis.defaultImg
                          : WholeApis.hostName + comment.cover),
                  maxRadius: 14,
                ),
                Container(
                  margin: const EdgeInsets.all(4.0),
                  child:
                      Text(comment.userName == null ? "匿名" : comment.userName),
                ),
              ],
            ),
          ),

          // 评论的内容
          Container(
            child: Text(
              comment.content,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 14,
              ),
            ),
          ),

          // 评论日期
          Container(
            child: Text(
              comment.publishTime.toString(),
              style: TextStyle(fontSize: 10, color: Colors.black38),
            ),
          ),
          SizedBox(
            height: .3,
            child: Container(
              color: Colors.black26,
            ),
          ),
        ],
      ),
    );
  }
}
